import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  message, 
  Popconfirm, 
  Tag, 
  Space,
  Card,
  Typography,
  Tooltip,
  Drawer,
  Descriptions,
  List,
  Avatar,
  Switch
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  UserOutlined,
  TeamOutlined,
  EyeOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { accountService } from '@/services/accountService';
import { Team, TeamMember } from '@/types/account';
import { useAuthStore } from '@/store/useAuthStore';

const { Title } = Typography;
const { TextArea } = Input;

// 简单的日期格式化函数
const formatDateTime = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN');
};

const TeamManagement: React.FC = () => {
  const { user } = useAuthStore();
  const [loading, setLoading] = useState(false);
  const [teams, setTeams] = useState<Team[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [selectedTeam, setSelectedTeam] = useState<Team | null>(null);
  const [teamMembers, setTeamMembers] = useState<TeamMember[]>([]);
  const [membersLoading, setMembersLoading] = useState(false);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();

  // 加载团队列表
  const loadTeams = async () => {
    setLoading(true);
    try {
      const response = await accountService.getTeams();
      const teamsData = response.data?.results || [];
      setTeams(teamsData);
    } catch (error: any) {
      message.error(error.response?.data?.message || '获取团队列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadTeams();
  }, []);

  // 创建团队
  const handleCreateTeam = async (values: any) => {
    try {
      await accountService.createTeam(values);
      message.success('团队创建成功');
      setCreateModalVisible(false);
      form.resetFields();
      loadTeams();
    } catch (error: any) {
      message.error(error.response?.data?.message || '创建团队失败');
    }
  };

  // 更新团队
  const handleUpdateTeam = async (values: any) => {
    if (!selectedTeam) return;
    try {
      await accountService.updateTeam(selectedTeam.id, values);
      message.success('团队信息更新成功');
      setEditModalVisible(false);
      editForm.resetFields();
      loadTeams();
    } catch (error: any) {
      message.error(error.response?.data?.message || '更新团队失败');
    }
  };

  // 删除团队
  const handleDeleteTeam = async (teamId: number) => {
    try {
      await accountService.deleteTeam(teamId);
      message.success('团队已删除');
      loadTeams();
    } catch (error: any) {
      message.error('删除团队失败');
    }
  };

  // 切换团队活跃状态
  const handleToggleTeamStatus = async (teamId: number, isActive: boolean) => {
    try {
      // 找到当前团队数据
      const currentTeam = teams.find(team => team.id === teamId);
      if (!currentTeam) {
        message.error('团队不存在');
        return;
      }
      
      // 使用updateTeam API更新团队状态
      await accountService.updateTeam(teamId, {
        name: currentTeam.name,
        description: currentTeam.description,
        password: '', // 不修改密码
        is_active: isActive // 更新活跃状态
      });
      
      message.success(`团队已${isActive ? '激活' : '禁用'}`);
      loadTeams();
    } catch (error: any) {
      message.error('更新团队状态失败');
    }
  };

  // 查看团队详情
  const handleViewTeam = async (team: Team) => {
    setSelectedTeam(team);
    setDetailDrawerVisible(true);
    await loadTeamMembers(team.id);
  };

  // 加载团队成员
  const loadTeamMembers = async (teamId: number) => {
    setMembersLoading(true);
    try {
      const response = await accountService.getTeamMembers(teamId);
      setTeamMembers(response.data || []);
    } catch (error: any) {
      message.error('获取团队成员失败');
    } finally {
      setMembersLoading(false);
    }
  };

  // 编辑团队
  const handleEditTeam = (team: Team) => {
    setSelectedTeam(team);
    editForm.setFieldsValue({
      name: team.name,
      description: team.description,
      password: '' // 密码字段不预填充
    });
    setEditModalVisible(true);
  };

  // 检查是否有权限编辑团队
  const canEditTeam = (team: Team) => {
    return user && (user.id === team.creator || user.admin_type === 'Super Admin');
  };

  // 检查是否有权限删除团队
  const canDeleteTeam = (team: Team) => {
    return user && (user.id === team.creator || user.admin_type === 'Super Admin');
  };

  // 检查是否有权限管理团队状态
  const canManageTeamStatus = (team: Team) => {
    return user && (user.id === team.creator || user.admin_type === 'Super Admin');
  };

  // 表格列定义
  const columns = [
    {
      title: '团队名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Team) => (
        <a onClick={() => handleViewTeam(record)} style={{ color: 'var(--primary-color)', cursor: 'pointer' }}>
          {text}
        </a>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '创建者',
      dataIndex: 'creator_name',
      key: 'creator_name',
      width: 120,
    },
    {
      title: '成员数量',
      dataIndex: 'member_count',
      key: 'member_count',
      width: 100,
      render: (count: number) => (
        <Tag color="blue">
          <UserOutlined /> {count} 人
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 120,
      render: (isActive: boolean, record: Team) => (
        <Switch
          checked={isActive}
          checkedChildren="活跃"
          unCheckedChildren="禁用"
          onChange={(checked) => handleToggleTeamStatus(record.id, checked)}
          disabled={!canManageTeamStatus(record)}
          size="small"
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_time',
      key: 'created_time',
      width: 180,
      render: (time: string) => formatDateTime(time),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_: any, record: Team) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small"
            icon={<EyeOutlined />} 
            onClick={() => handleViewTeam(record)}
          >
            查看
          </Button>
          {canEditTeam(record) && (
            <Button 
              type="link" 
              size="small"
              icon={<EditOutlined />} 
              onClick={() => handleEditTeam(record)}
            >
              编辑
            </Button>
          )}
          {canDeleteTeam(record) && (
            <Popconfirm
              title="确定要删除这个团队吗？"
              onConfirm={() => handleDeleteTeam(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                danger 
                size="small"
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4} style={{ margin: 0 }}>
          <TeamOutlined /> 团队管理
        </Title>
        <Space>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={loadTeams}
            loading={loading}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => setCreateModalVisible(true)}
          >
            创建团队
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={teams || []}
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 20,
          showSizeChanger: false,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个团队`,
        }}
        size="small"
      />

      {/* 创建团队的模态框 */}
      <Modal
        title="创建团队"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateTeam}
        >
          <Form.Item
            name="name"
            label="团队名称"
            rules={[
              { required: true, message: '请输入团队名称' },
              { max: 50, message: '团队名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入团队名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="团队描述"
            rules={[
              { max: 200, message: '团队描述不能超过200个字符' }
            ]}
          >
            <TextArea 
              rows={4} 
              placeholder="请输入团队描述（可选）" 
            />
          </Form.Item>
          <Form.Item
            name="password"
            label="团队密码"
            rules={[
              { required: true, message: '请输入团队密码' },
              { min: 6, message: '密码长度不能少于6位' }
            ]}
          >
            <Input.Password placeholder="请输入团队密码" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                创建
              </Button>
              <Button onClick={() => {
                setCreateModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑团队的模态框 */}
      <Modal
        title="编辑团队"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          editForm.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleUpdateTeam}
        >
          <Form.Item
            name="name"
            label="团队名称"
            rules={[
              { required: true, message: '请输入团队名称' },
              { max: 50, message: '团队名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入团队名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="团队描述"
            rules={[
              { max: 200, message: '团队描述不能超过200个字符' }
            ]}
          >
            <TextArea 
              rows={4} 
              placeholder="请输入团队描述（可选）" 
            />
          </Form.Item>
          <Form.Item
            name="password"
            label="新密码"
            rules={[
              { min: 6, message: '密码长度不能少于6位' }
            ]}
          >
            <Input.Password placeholder="留空则不修改密码" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                更新
              </Button>
              <Button onClick={() => {
                setEditModalVisible(false);
                editForm.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 团队详情抽屉 */}
      <Drawer
        title="团队详情"
        placement="right"
        width={600}
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
      >
        {selectedTeam && (
          <>
            <Descriptions column={1} bordered size="small" style={{ marginBottom: 24 }}>
              <Descriptions.Item label="团队名称">{selectedTeam.name}</Descriptions.Item>
              <Descriptions.Item label="团队描述">{selectedTeam.description || '-'}</Descriptions.Item>
              <Descriptions.Item label="创建者">{selectedTeam.creator_name}</Descriptions.Item>
              <Descriptions.Item label="成员数量">
                <Tag color="blue">
                  <UserOutlined /> {selectedTeam.member_count} 人
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={selectedTeam.is_active ? 'green' : 'red'}>
                  {selectedTeam.is_active ? '活跃' : '禁用'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{formatDateTime(selectedTeam.created_time)}</Descriptions.Item>
            </Descriptions>

            <Title level={5}>团队成员</Title>
            <List
              loading={membersLoading}
              dataSource={teamMembers || []}
              renderItem={(member) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar icon={<UserOutlined />} />}
                    title={member.username}
                    description={`${member.email} • 加入时间：${formatDateTime(member.joined_time)}`}
                  />
                </List.Item>
              )}
              locale={{
                emptyText: '暂无成员'
              }}
            />
          </>
        )}
      </Drawer>
    </Card>
  );
};

export default TeamManagement;
